# _*_ coding: utf-8 _*_


__author__ = 'yinlei'
__date__ = '2018-05-18 9:29'

from datetime import datetime

from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

from main import create_app
from apps.cms.models import *
from apps.front.models import *
from apps.models import Banner,BoardModel,PostModel,CommentModel,HighlightPostModel

app = create_app()
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)


@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
@manager.option('-e', '--email', dest='email')
def create_cms_user(username, password, email):
    with db.auto_commit():
        user = CMSUser(username=username, password=password, email=email)
        db.session.add(user)
@manager.option('-m','--mobile',dest='mobile')
@manager.option('-u','--username',dest='username')
@manager.option('-p','--password',dest='password')
def create_front_user(mobile,username,password):
    with db.auto_commit():
        user = FrontUser(mobile=mobile,username=username,password=password)
        db.session.add(user)


@manager.command
def create_role():
    # 1.访问者只能修改个人信息
    visitor = CMSRole()
    visitor.name = '访问者'
    visitor.desc = '只能查看数据不能修改'
    visitor.permissions = CMSPermission.VISITOR
    # 2.运营角色(修改个人信息,管理帖子,管理评论,管理前台用户)
    operator = CMSRole()
    operator.name = '运营'
    operator.desc = '管理帖子,管理评论,管理前台用户'
    operator.permissions = CMSPermission.VISITOR | CMSPermission.COMMENTER | CMSPermission.POSTER | CMSPermission.FRONTUSER|CMSPermission.CMSUSER
    #3.管理员
    admin = CMSRole()
    admin.name = '管理员'
    admin.desc = '拥有所有的权限'
    admin.permissions =CMSPermission.VISITOR | CMSPermission.COMMENTER | CMSPermission.POSTER | CMSPermission.FRONTUSER|CMSPermission.CMSUSER|CMSPermission.BOARDER
    #4.开发者
    developer = CMSRole()
    developer.name = '开发者'
    developer.desc = '开发者专用权限'
    developer.permissions = CMSPermission.ALL_PERMISSION
    db.session.add_all([visitor,operator,admin,developer])
    db.session.commit()
@manager.option('-e','--email',dest='email')
@manager.option('-n','--name',dest='name')
def add_user_to_role(email,name):
    user = CMSUser.query.filter_by(email=email).first()
    if user:

        role = CMSRole.query.filter_by(name=name).first()
        if role:
            print(role.name)
            user.roles.append(role)
            db.session.commit()
            print('添加角色成功')
        else:
            print('没有这个角色')
    else:
        print('邮箱不存在')

@manager.option('-e', '--email',dest='email')
def test_permission(email):
    user = CMSUser.query.filter_by(email=email).first()
    if user:
        if user.has_permiss(CMSPermission.ALL_PERMISSION):
            print('用户有访问权限')
        else:
            print('用户无访问权限')
    else:
        print('没有该用户')

if __name__ == '__main__':
    manager.run()
